//
//  SleepModel.m
//  project
//
//  Created by 黄建华 on 2018/2/5.
//  Copyright © 2018年 黄建华. All rights reserved.
//

#import "SleepModel.h"

/***************************************************睡眠模型***********************************************/
@implementation SleepSubModel
- (instancetype)init {
    self = [super init];
    if (self) {
        _subdeep          = 0;
        _sublight         = 0;
        _subsober         = 0;
        _subCompare       = 0.0;
        _subeffDuration   = 0;
        _subtotalduration = 0;
        _substartTime     = @"";
        _subendTime       = @"";
        _subdate          = [[NSDate date] dateToDayString];
    }
    return self;
}

- (NSArray *)subsleepData {
    return _subsleepData ? _subsleepData : @[];
}

@end

@implementation SleepModel
- (instancetype)init {
    self = [super init];
    if (self) {
        _user_id     = SN_USER.user_id;
        _dateString  = [[NSDate date] dateToDayString];
        _sleepFinish = 1;
    }
    
    return self;
}

- (void)updateToDBSafely {
    NSString *where = [NSString stringWithFormat:@"user_id = '%@' and dateString = '%@'",
                       SN_USER.user_id, self.dateString];
    SleepModel *model = [SleepModel searchSingleWithWhere:where orderBy:nil];
    
    if (model) {
        [SleepModel updateToDB:self where:nil];
    }
}

+ (SleepModel *)initWithDate:(NSDate *)date {
    SleepModel *model = [[SleepModel alloc] init];
    
    model.dateString = [date dateToDayString];
    model.user_id    = SN_USER.user_id;
    //睡眠初始
    model.deeps          = 0;
    model.lights         = 0;
    model.sobers         = 0;
    model.durations      = 0;
    model.effDuration    = 0;
    model.compareEff     = 0.0;
    model.compareDeep    = 0.0;
    model.compareLight   = 0.0;
    model.compareSober   = 0.0;
    model.sleepquality   = NO;
    model.compareQuality = SN_Text(@"暂无数据");
    model.sleepFinish    = 1;
    return model;
}

+ (SleepModel *)getSleepModelFromDB {
    SleepModel *model = [SleepModel getSleepModelFromDBWith:[NSDate date]];
    
    return model;
}

+ (SleepModel *)getSleepModelFromDBWithDayString:(NSString *)string {
    NSString *where = [NSString stringWithFormat:@"user_id = '%@' and dateString = '%@'",
                       SN_USER.user_id, string];
    SleepModel *model = [SleepModel searchSingleWithWhere:where orderBy:nil];
    
    if (!model) {
        model             = [[SleepModel alloc] init];
        model.dateString  = string;
        model.user_id     = SN_USER.user_id;
        model.sleepFinish = 1;
        [model updateToDB];
    }
    return model;
}

+ (SleepModel *)getSleepModelFromDBWith:(NSDate *)date {
    NSString *where = [NSString stringWithFormat:@"user_id = '%@' and dateString = '%@'",
                       SN_USER.user_id, [date dateToDayString]];
    SleepModel *model = [SleepModel searchSingleWithWhere:where orderBy:nil];
    
    if (!model) {
        model = [SleepModel pedometerSaveEmptyModelToDBWithDate:date isSaveAllDay:NO];
    }
    model.sleepFinish = 1;
    return model;
}

+ (SleepModel *)pedometerSaveEmptyModelToDBWithDate:(NSDate *)date isSaveAllDay:(BOOL)save {
    SleepModel *model = [SleepModel initWithDate:date];
    
    [SleepModel creatEmptyDataArrayWithModel:model];
    if (![date compareWithDate:[NSDate date]] &&
        [date timeIntervalSince1970] < [[NSDate date] timeIntervalSince1970]) {
        // NSLog(@"model.isSaveAllDay = ..%@", date);
        if (save) {
            model.isSaveAllDay = YES;
        }
    }
    
    [model saveToDB];
    
    return model;
}

// 为模型创建空值的对象
+ (void)creatEmptyDataArrayWithModel:(SleepModel *)model
{
}

// 表名
+ (NSString *)getTableName
{
    return @"SleepModel";
}

// 复合主键
+ (NSArray *)getPrimaryKeyUnionArray
{
    return @[@"user_id", @"dateString"];
}

// 表版本
+ (int)getTableVersion
{
    return 1;
}

+ (void)initialize
{
    [super initialize];
    
    [self bindYYJSONKey:@"deep" toProperty:@"deeps"];
    [self bindYYJSONKey:@"duration" toProperty:@"durations"];
    [self bindYYJSONKey:@"light" toProperty:@"lights"];
    [self bindYYJSONKey:@"sober" toProperty:@"sobers"];
    [self bindYYJSONKey:@"data" toProperty:@"detailData"];
    [self bindYYJSONKey:@"date" toProperty:@"dateString"];
    
    [self removePropertyWithColumnName:@"detailData"];
}

// 睡眠大数据
+ (void)updateSleepData:(NSData *)sleepData {
    UInt8 val[20] = {0};
    
    [sleepData getBytes:&val length:sleepData.length];
    NSString *content = [NSString stringWithFormat:@"%@", sleepData];
    BOOL isBagHead = (val[3] % 4)==0?YES:NO;
    if (val[3] == 0) {
        SN_PublicClass.todaySleepArray = [NSMutableArray array];
        SN_PublicClass.yesSleepArray   = [NSMutableArray array];
    }
    LogWrite(@"睡眠大数据", content, nil);
    if (isBagHead) {
        SN_PublicClass.sleepSubModel          = [[SleepSubModel alloc] init];
        SN_PublicClass.sleepSubModel.subdeep  = 0;
        SN_PublicClass.sleepSubModel.sublight = 0;
        SN_PublicClass.sleepSubModel.subsober = 0;
        SN_PublicClass.sleepDetailArr         = [NSMutableArray array];
        
        NSString *startTime = [NSString stringWithFormat:@"%04d-%02d-%02d %02d:%02d:00", val[4] + 2000,
                               val[5], val[6], val[7], val[8]];
        NSString *endTime = [NSString stringWithFormat:@"%04d-%02d-%02d %02d:%02d:00", val[9] + 2000,
                             val[10], val[11], val[12], val[13]];
        SN_PublicClass.sleepSubModel.substartTime = startTime;
        SN_PublicClass.sleepSubModel.subendTime   = endTime;
        SN_PublicClass.sleepSubModel.subdate      = [endTime componentsSeparatedByString:@" "][0];
        
        // 判断这一次睡眠到底是今天或者是昨天
        if ([SN_PublicClass.sleepSubModel.subdate isEqualToString:SN_PublicClass.todaymodel.dateString]) {
            [SN_PublicClass.todaySleepArray addObject:SN_PublicClass.sleepSubModel];
        } else if ([SN_PublicClass.sleepSubModel.subdate isEqualToString:SN_PublicClass.yesModel.dateString]) {
            [SN_PublicClass.yesSleepArray addObject:SN_PublicClass.sleepSubModel];
        }
    } else {
        for (int i = 4; i < 19; i += 2) {
            NSInteger number      = val[i] * 256 + val[i + 1];
            NSInteger sleepStatus = (UInt8)(number >> 14);
            NSInteger sleepTime   = (UInt16)number & 0x3FFF;
            if (sleepStatus == 0) {
                SN_PublicClass.sleepSubModel.sublight += sleepTime;
            } else if (sleepStatus == 1) {
                SN_PublicClass.sleepSubModel.subdeep += sleepTime;
            } else if (sleepStatus == 2) {
                SN_PublicClass.sleepSubModel.subsober += sleepTime;
            }
            [SN_PublicClass.sleepDetailArr addObject:StrByInt(number)];
        }
        SN_PublicClass.sleepSubModel.subtotalduration = SN_PublicClass.sleepSubModel.sublight + SN_PublicClass.sleepSubModel.subdeep + SN_PublicClass.sleepSubModel.subsober;
        SN_PublicClass.sleepSubModel.subeffDuration   = SN_PublicClass.sleepSubModel.subdeep + SN_PublicClass.sleepSubModel.sublight;
        SN_PublicClass.sleepSubModel.subCompare       = SN_PublicClass.sleepSubModel.subeffDuration / SN_PublicClass.sleepSubModel.subtotalduration;
        SN_PublicClass.sleepSubModel.subsleepData     = [NSArray arrayWithArray:SN_PublicClass.sleepDetailArr];
    }
}

+ (void)sleepTransEnd {
    SleepModel     *tmodel = SN_PublicClass.todaySleep;
    int            tDeep   = 0;
    int            tlight  = 0;
    int            tSober  = 0;
    NSMutableArray *tarray = [NSMutableArray array];
    
    for (int i = 0; i < SN_PublicClass.todaySleepArray.count; i++) {
        SleepSubModel *tModel = [SN_PublicClass.todaySleepArray objectAtIndex:i];
        tDeep  += tModel.subdeep;
        tlight += tModel.sublight;
        tSober += tModel.subsober;
        [tarray addObject:StrByInt(tModel.subtotalduration)];
    }
    
    CGFloat tmaxValue = [[tarray valueForKeyPath:@"@max.floatValue"] floatValue];
    
    tmodel.maxDurations   = tmaxValue;
    tmodel.deeps          = tDeep;
    tmodel.lights         = tlight;
    tmodel.sobers         = tSober;
    tmodel.durations      = tDeep + tlight + tSober;
    tmodel.effDuration    = tDeep + tlight;
    tmodel.sleepsubArray  = [NSMutableArray arrayWithArray:SN_PublicClass.todaySleepArray];
    tmodel.compareEff     = 1.0 *tmodel.effDuration/tmodel.durations;
    tmodel.compareDeep    = (float)(1.00 *(tDeep)/tmodel.durations *100);
    tmodel.compareLight   = (float)(1.00 *(tlight)/tmodel.durations *100);
    tmodel.compareSober   = (float)(1.00 *(tSober)/tmodel.durations *100);
    tmodel.compareQuality = [SleepModel WithQuality:tmodel.compareEff];
    if (tmodel.compareEff >= 0.7) {
        tmodel.sleepquality = YES;
    } else {
        tmodel.sleepquality = NO;
    }
    
    LogWrite(@"睡眠大数据同步结束", ([NSString stringWithFormat:@"%ld",(long)tmodel.durations]), tmodel.durations>=1440?@"今日睡眠时长异常":@"正常");
    if (tmodel.durations>=1440) {
        ErrorTimes++;
        [[NSUserDefaults standardUserDefaults] setInteger:ErrorTimes forKey:[NSDate date].dateToDayString];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    SleepModel     *ymodel = SN_PublicClass.yesSleep;
    int            yDeep   = 0;
    int            ylight  = 0;
    int            ySober  = 0;
    NSMutableArray *yarray = [NSMutableArray array];
    for (int i = 0; i < SN_PublicClass.yesSleepArray.count; i++) {
        SleepSubModel *yModel = [SN_PublicClass.yesSleepArray objectAtIndex:i];
        yDeep  += yModel.subdeep;
        ylight += yModel.sublight;
        ySober += yModel.subsober;
        [yarray addObject:StrByInt(yModel.subtotalduration)];
    }
    
    CGFloat ymaxValue = [[yarray valueForKeyPath:@"@max.floatValue"] floatValue];
    
    ymodel.maxDurations   = ymaxValue;
    ymodel.deeps          = yDeep;
    ymodel.lights         = ylight;
    ymodel.sobers         = ySober;
    ymodel.durations      = yDeep + ylight + ySober;
    ymodel.effDuration    = yDeep + ylight;
    ymodel.sleepsubArray  = [NSMutableArray arrayWithArray:SN_PublicClass.yesSleepArray];
    ymodel.compareEff     = 1.0 *ymodel.effDuration/ymodel.durations;
    ymodel.compareDeep    = (float)(1.00 *(yDeep)/ymodel.durations *100);
    ymodel.compareLight   = (float)(1.00 *(ylight)/ymodel.durations *100);
    ymodel.compareSober   = (float)(1.00 *(ySober)/ymodel.durations *100);
    ymodel.compareQuality = [SleepModel WithQuality:ymodel.compareEff];
    if (ymodel.compareEff >= 0.7) {
        ymodel.sleepquality = YES;
    } else {
        ymodel.sleepquality = NO;
    }
    [tmodel updateToDB];
    [ymodel updateToDB];
    [SN_Net updateEveryModelWithType:HJUpdateSleep];
    LogWrite(@"睡眠大数据同步结束", ([NSString stringWithFormat:@"%ld",(long)ymodel.durations]),ymodel.durations>=1440?@"昨日睡眠时长异常":@"正常");
    if (ymodel.durations>=1440) {
        ErrorTimes++;
        [[NSUserDefaults standardUserDefaults] setInteger:ErrorTimes forKey:[NSDate date].dateToDayString];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    NSLog(@"今日睡眠>>>%d",tmodel.durations);
    NSLog(@"昨天睡眠>>>%d",ymodel.durations);
    NSLog(@"睡眠数据同步完成>>>");
}

+ (NSString *)WithQuality:(float)sleepQuality {
    if (sleepQuality >= 0.75) {
        return SN_Text(@"优秀");
    } else if (sleepQuality >= 0.6 &sleepQuality < 0.75) {
        return SN_Text(@"良好");
    } else if (sleepQuality >= 0.4 &sleepQuality < 0.6) {
        return SN_Text(@"一般");
    } else {
        return SN_Text(@"较差");
    }
}

//同步下载数据需要的
- (void)saveToDBByDownload
{
    self.effDuration = self.deeps + self.lights;
    if (self.durations > 0) {
        self.compareEff = 1.0 *self.effDuration / self.durations;
        self.compareDeep = (int)(1.0 *(self.deeps) / self.durations * 100);
        self.compareLight = (int)(1.0 *(self.lights) / self.durations * 100);
        self.compareSober = (int)(1.0 *(self.sobers) / self.durations * 100);
        self.compareQuality = [SleepModel WithQuality:self.compareEff];
        if (self.compareEff >= 0.7) {
            self.sleepquality = YES;
        } else {
            self.sleepquality = NO;
        }
    }
    
    NSArray *array = (NSArray *)[self.detailData parseJSONString];
    if ([array isKindOfClass:NSArray.class] && array.count > 0) {
        self.sleepsubArray = [NSMutableArray array];
        for (int i = 0; i < array.count ; i++) {
            NSDictionary *dict = array[i];
            if ([dict isKindOfClass:NSDictionary.class] && dict.allKeys.count > 0) {
                SleepSubModel *model = [[SleepSubModel alloc] init];
                model.substartTime = dict[@"startTime"];
                model.subendTime   = dict[@"endTime"];
                model.subdate      = [model.subendTime componentsSeparatedByString:@" "][0];
                NSArray *detailArr = dict[@"sleepData"];
                if ([array isKindOfClass:NSArray.class] && array.count > 0) {
                    NSMutableArray *subDetailArr = [NSMutableArray array];
                    for (NSString *string in detailArr) {
                        NSInteger number = string.integerValue;
                        NSInteger sleepStatus = (UInt8)(number >> 14);
                        NSInteger sleepTime   = (UInt16)number & 0x3FFF;
                        if (sleepStatus == 0) {
                            model.sublight += sleepTime;
                        } else if (sleepStatus == 1) {
                            model.subdeep += sleepTime;
                        } else if (sleepStatus == 2) {
                            model.subsober += sleepTime;
                        }
                        
                        [subDetailArr addObject:StrByInt(number)];
                    }
                    
                    model.subtotalduration = model.sublight + model.subdeep + model.subsober;
                    model.subeffDuration = model.subdeep + model.sublight;
                    if (model.subtotalduration > 0) {
                        model.subCompare = model.subeffDuration * 1.0 / model.subtotalduration;
                    }
                    
                    model.subsleepData = [NSArray arrayWithArray:subDetailArr];
                }
                [self.sleepsubArray addObject:model];
            }
        }
    }
    
    NSString *todayStr = [[NSDate date] dateToDayString];
    if (self.dateString != todayStr) {
        self.isSaveAllDay = YES;
    }
    
    [self updateToDB];
}

@end

